#include "Listener.h"
#include "../config/Config.h"
#include "../smtp/core/StartTLSReceiver.h"
#include "../smtp/core/SSLReceiver.h"

using namespace kc_sf;

// ------------------------------------------------------ //

Listener::Listener()
{
	Config &cfg = Config::getInstance();
	int max_connections = cfg.cMaxSessions;
	int max_ssl_connections = max_connections / 3;
	int max_starttls_connections = max_connections - max_ssl_connections;
	int port = cfg.cListenPort, ssl_port = cfg.cSslListenPort;

	l_starttls_server = new TCPServer( port, max_starttls_connections, new StartTLSReceiver() );
	l_ssl_server = new SSLServer( ssl_port, max_ssl_connections, new SSLReceiver() );

	l_logger << detail << listener << "Serwer rozpoczął nasłuch na porcie " << port << ". Oczekiwanie na połączenia typu StartTLS." << flush;
	l_logger << detail << listener << "Serwer rozpoczął nasłuch na porcie " << ssl_port << ". Oczekiwanie na połączenia szyfrowane." << flush;
}

// ------------------------------------------------------ //

Listener::~Listener()
{
	stop();

	if( l_starttls_server )
		delete l_starttls_server;

	if( l_ssl_server )
		delete l_ssl_server;

	l_listeners.join_all();
}

// ------------------------------------------------------ //

void Listener::start()
{
	boost::thread *starttls_thread = new boost::thread( &TCPServer::startListening, l_starttls_server );
	boost::thread *ssl_thread = new boost::thread( &SSLServer::startListening, l_ssl_server );

	l_listeners.add_thread( starttls_thread );
	l_listeners.add_thread( ssl_thread );
	l_listeners.join_all();
}

// ------------------------------------------------------ //

void Listener::stop()
{
	l_listeners.interrupt_all();

	if( l_starttls_server )
	{
		l_starttls_server->closeAllConnections();
		l_starttls_server->stopListening();
	}

	if( l_ssl_server )
	{
		l_ssl_server->closeAllConnections();
		l_ssl_server->stopListening();
	}
	l_logger << info << listener << "Zakończono pracę" << flush;
}

